<template>
  <main>
    <div>
      <div v-if="pending">
        Pending...
      </div>
      <div v-else>
        <p>Edit :{{ file }}</p>

        <form @submit.prevent="" @change="onFileChange" class="my-3">
          <v-text-field v-model="file.name" type="text" />

          <v-select v-model="file.status" :items="['PENDING', 'READY', 'DELETED', 'ERROR']">
          </v-select>

          <v-btn @click="cancel" class="ma-5">Annuler</v-btn>
          <v-btn @click="save" class="ma-5">Enregistrer</v-btn>
          <v-btn @click="deleteAndGoBack" class="ma-5">Supprimer</v-btn>
          <v-btn @click="refresh" class="ma-5">Refresh</v-btn>
          <v-btn @click="goBack" class="ma-5">Retour</v-btn>
        </form>
      </div>
    </div>
  </main>
</template>

<script setup lang="ts">
import {useEntityManager} from "~/composables/data/useEntityManager";
import {computed, ComputedRef, ref, Ref} from "@vue/reactivity";
import {File} from "~/models/Core/File";
import {navigateTo, useRoute} from "#app";
import {useEntityFetch} from "~/composables/data/useEntityFetch";

const route = useRoute()

const id: Ref<number> = ref(parseInt(route.params.id as string))

const em = useEntityManager()

const { pending, refresh } = useEntityFetch(File, id)

// Get file from store
const file: ComputedRef<File> = computed( () => {
  return em.find(File, id.value)
})

// Update store when form is changed
const onFileChange = () => {
  em.save(File, file.value)
}

const save = async () => {
  await em.persist(File, file.value)
}

const cancel = async () => {
  if (em.isNewEntity(File, id.value)) {
    await em.delete(File, file.value)
  } else {
    em.reset(File, file.value)
  }
}

const deleteItem = async () => {
  await em.delete(File, file.value)
}

const goBack = () => {
  navigateTo('/poc')
}

const saveAndGoBack = async () => {
  await save()
  goBack()
}

const cancelAndGoBack = async () => {
  await cancel()
  goBack()
}

const deleteAndGoBack = async () => {
  await deleteItem()
  goBack()
}
</script>

<style>
</style>
